//
//  CWJavaScriptApiPage.m
//  CWDevelop
//
//  Created by LittoCats on 7/10/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWJavaScriptApiPage.h"
#import "CWViewController.h"
#import "CWFile.h"
#import <objc/message.h>

#import "UIView+CWToast.h"

#define PAGEID action[@"page"]
#define PAGE action[@"__PAGEID"]

@implementation CWJavaScriptApiPage

+ (void)analyseAction:(NSMutableDictionary *)action
{
    [super analyseAction:action];
    
//    解析当前的工作路径(current viewcontroller<page>)
//    当 action 中没有"page"时，从当前jsContext中取出pageid
    NSString *pageId = !PAGEID || [PAGEID isEmpty] ? [CWJSCONTEXT evaluateScript:@"_page"] : PAGEID;
    if (!pageId){
        CWLog(@"[CWJavaScriptAPI] warning : Page.id is not exist < domain : page >.");
        return;
    }
    NSObject *page = [NSObject findInstanceWithId:pageId];

    //切换 jsContext
    SEL fetchPageJSContext = NSSelectorFromString(@"jsContext");
    CWJavaScriptContext *currentContext = [page respondsToSelector:fetchPageJSContext] ? objc_msgSend(page, fetchPageJSContext) : CWJSCONTEXT;
    
    [action setObject:pageId forKey:@"page"];
    page ? [action setObject:[NSObject findInstanceWithId:PAGEID] forKey:@"__PAGEID"] : nil;
    currentContext ? [action setObject:currentContext forKey:kJavaScriptContextKey] : nil;
}

#pragma mark-

CWJavascriptApi(open)
{
    NSArray *entries = [PAGEID componentsSeparatedByString:@">>"];
    NSString *identifier = [entries lastObject];
    if (!identifier || [identifier isEmpty])
        identifier = [[[entries firstObject] componentsSeparatedByString:@"/"] lastObject];
    if (!identifier || [identifier isEmpty])
        identifier = [NSString stringWithFormat:@"page_%i",arc4random()%10000];
    CWViewController *vc = [CWViewController controllerWithId:identifier];
    if (vc){
        [[UINavigationController defaultNavigationController] popToViewController:vc animated:NO];
        return;
    }
    
    //解析路径
    NSString *currentPath = [entries firstObject];
    currentPath = [currentPath hasPrefix:@"./"] ? [NSString stringWithFormat:@"%@%@",[CWJSCONTEXT evaluateScript:@"__path"],[currentPath substringFromIndex:1]] :
                    [NSString stringWithFormat:@"%@/%@",[CWFile appRootPath],currentPath];
    
    [params[@"params"] setObject:currentPath forKey:@"__path"];
    vc = [[CWViewController alloc] initWithIdentifier:identifier params:params[@"params"]];
    [UINavigationController pushViewController:vc asRoot:[params[@"asRoot"] boolValue]];
}

#pragma mark- life circle

CWJavascriptApi(onCreated)
{
    [[PAGE params] setObject:[CWScriptFunction functionWithFunctionScript:params context:[CWJSCONTEXT _id]] forKey:[NSString stringWithFormat:@"__onCreated_%p",[PAGE _id]]];
}

CWJavascriptApi(onResume)
{
    [[PAGE params] setObject:[CWScriptFunction functionWithFunctionScript:params context:[CWJSCONTEXT _id]] forKey:[NSString stringWithFormat:@"__onResume_%p",[PAGE _id]]];
}

CWJavascriptApi(onPause)
{
    [[PAGE params] setObject:[CWScriptFunction functionWithFunctionScript:params context:[CWJSCONTEXT _id]] forKey:[NSString stringWithFormat:@"__onPause_%p",[PAGE _id]]];
}

#pragma mark- 

CWJavascriptApi(param)
{
    NSMutableDictionary *data = [PAGE params];
    if ([params isKindOfClass:[NSString class]]) {
        [CWJSCALLBACK evaluateWithArguments:data[params], nil];
        return;
    }
    if ([params isKindOfClass:[NSArray class]]) {
        NSMutableArray *result = [NSMutableArray new];
        for (id key in params)
            if ([key isKindOfClass:[NSString class]])
                [result addObject:data[key]];
        [CWJSCALLBACK evaluateWithArguments:result, nil];
        return;
    }
    
    if ([params isKindOfClass:[NSDictionary class]])
        for (NSString *key in [params allKeys])
            [data setObject:params[key] forKey:key];
}

#pragma mark-
CWJavascriptApi(showActivity)
{
    [[PAGE view] makeToastActivityWithMessage:params];
}
@end
